package com.laikan.reader.bookfriend.activity;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.MaterBean;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.utils.PublicUtil;
import com.socks.library.KLog;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/5/4.
 */
public class BirthdayActivity extends BasicActivity implements View.OnClickListener {

    private TextView birth_Day;
    private TextView save;
    private String date; //为时间格式的字符串例如："2016-02-02"
    private ImageView back_tv;
    private RelativeLayout birth_top;
    private String birth;
    Drawable drawable_back_tv;
    private RelativeLayout back_layout;
    private LoadingDialog mloadingDialog;

    public String $(int n) {
        return n < 10 ? "0" + n : String.valueOf(n);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_date);
        save = (TextView)findViewById(R.id.tv_save);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        birth_Day = (TextView)findViewById(R.id.tv_display_birthday);
        birth_top = (RelativeLayout)findViewById(R.id.birth_top);
    }

    @Override
    protected void initData() {
        mloadingDialog = new LoadingDialog(mContext);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        birth = getIntent().getStringExtra("birthday");
        //        KLog.d("TAG", "birth =" + birth);
        birth_Day.setText(birth);
        //     showDateDialog();
    }

    public void showDateDialog(int year, int month, int day) {
        int mYear = year;
        int mMonth = month;
        int mDay = day;
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                birth_Day.setText(year + "-" + $(monthOfYear + 1) + "-" + $(dayOfMonth));
            }
        }, mYear, mMonth, mDay);

        dialog.show();
    }

    //    public void showDateDialog(){
    //        Calendar c = Calendar.getInstance();
    //        int year = c.get(Calendar.YEAR);
    //        int month = c.get(Calendar.MONTH);
    //        int day = c.get(Calendar.DAY_OF_MONTH);
    //        DatePickerDialog dialog  = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
    //
    //            @Override
    //            public void onDateSet(DatePicker view, int year, int monthOfYear,
    //                                  int dayOfMonth) {
    //                birth_Day.setText(year + "-" + $(monthOfYear + 1) + "-"
    //                        + $(dayOfMonth));
    //            }
    //        }, year, month, day);
    //
    //        dialog.show();
    //    }
    @Override
    protected void setListener() {
        save.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        birth_top.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_save:
                date = birth_Day.getText().toString();
                submit();
                break;
            case R.id.back_layout:
                finish();
                break;
            case R.id.birth_top:
                date = birth_Day.getText().toString();
                int year = Integer.parseInt(date.substring(0, 4));
                int month = Integer.parseInt(date.substring(5, 7));
                int day = Integer.parseInt(date.substring(8, 10));
                if (birth_Day.getText().equals("2000-01-01")) {
                    showDateDialog(2000, 00, 01);
                }else {showDateDialog(year, month - 1, day);}
                break;
            default:
                break;
        }
    }

    //    /*将字符串转为时间戳*/
    //    public long getStringToDate(String time) {
    //        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //        Date date = new Date();
    //        try{
    //           date = sdf.parse(time);
    //           } catch(Exception e) {
    //
    //            e.printStackTrace();
    //            }
    //        return date.getTime();
    //        }

    /**
     * 将出生日期保存到服务器
     */
    private void submit() {
        mloadingDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("birthday", date);
        map.put("gender", "0"); //上行性别的意义？
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mloadingDialog.dismiss();
                BaseDataBean<MaterBean> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<MaterBean>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (result.getData() == null && !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            if (result.getData().isStatus()) {
                                ToastMgr.showShortToast(R.string.gender_modify_success);
                                Intent intent = new Intent();
                                intent.putExtra("return_birth", date);
                                setResult(RESULT_OK, intent);
                                finish();
                            }else {
                                ToastMgr.showShortToast(R.string.gender_modify_failed);
                            }
                        }
                    }else {
                        ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    }
                }catch (Exception e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mloadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。30");
            }

            @Override
            public void onFinish() {

            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_date);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }
}
